using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Geekeradmin.Filters
{
    /// <summary>
    /// 资源缓存过滤器
    /// 执行步骤：OnResourceExecuting》构造函数》Action方法》OnResourceExecuted》
    /// </summary>
    public class CustomResource : Attribute, IResourceFilter, IFilterMetadata
    {
        private static Dictionary<string, object> keyValues = new Dictionary<string, object>();

        /// <summary>
        /// 设置过期时间（单位：秒）
        /// </summary>
        /// <param name="Duration"></param>
        public CustomResource(int Duration = 10)
        {
            this.Duration = Duration;
        }
        public int Duration { get; set; }

        /// <summary>
        /// 方法执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            //判断当前访问的Action上/当前Action所在的控制器上标记的所有特性是否保护某个特性
            if(context.ActionDescriptor.EndpointMetadata.Any(o => o.GetType().Equals(typeof(CustomAllowAnonymous))))
            {
                return;
            }
            var key = context.HttpContext.Request.Path;
            if (keyValues.ContainsKey(key))
            {
                context.Result = (IActionResult)keyValues[key];
            }
            Console.WriteLine("OnResourceExecuting.....");
        }

        /// <summary>
        /// 方法执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            //判断当前访问的Action上/当前Action所在的控制器上标记的所有特性是否保护某个特性
            if (context.ActionDescriptor.EndpointMetadata.Any(o => o.GetType().Equals(typeof(CustomAllowAnonymous))))
            {
                return;
            }
            var key = context.HttpContext.Request.Path;
            keyValues[key] = context.Result;
            Console.WriteLine("OnResourceExecuted.....");
        }

    }
}
